/**
 * 统一处理请求参数，控制器接收到的永远是 明文 {[key:string]:any}
 *  前端传过来(req.query | req.body)的格式始终为
 *    {
 *      [CustomKey.Params]:string | {[key:string]:any}
 *    }
 *  加密模式：[CustomKey.Params]值为string，密文
 *  传统模式：[CustomKey.Params]值为{[key:string]:any}，明文
 * */

import { Injectable, NestMiddleware } from "@nestjs/common";
import { Request, Response } from "express";
import { CryptoTool } from "src/tools/crypto.tool";
import { CustomKey } from "src/utils/Mapping";
import * as QueryString from "querystring";
import configuration from "src/config/configuration";

@Injectable()
export class ReqMiddleware implements NestMiddleware {
  config = configuration()

  use(req: Request, res: Response, next: (error?: any) => void): any {
    // 入参解密
    if(this.config.IS_ENCRYPT) {
      if(req.query[CustomKey.Params]) req.query = JSON.parse(CryptoTool.decryptDbData(req.query[CustomKey.Params] as string));
      if(req.body[CustomKey.Params]) req.body = JSON.parse(CryptoTool.decryptDbData(req.body[CustomKey.Params] as string));
    } else {
      if(req.query[CustomKey.Params]) req.query = req.query[CustomKey.Params] as QueryString.ParsedUrlQuery;
      if(req.body[CustomKey.Params]) req.body = req.query[CustomKey.Params];
    }
    next();
  }
}
